package cn.tedu.system.user.service;

import cn.tedu.system.user.mapper.UserMapper;
import cn.tedu.system.user.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;


public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    /**登录认证时系统底层会调用此方法
     * @param username 用户登录时输入的用户名
     * */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.基于用户名查询用户
        SysUser user = userMapper.selectByUsername(username);
        if(user==null||user.getValid()==0)
            throw new UsernameNotFoundException("用户名不存在");
        //2.基于用户id查询用户权限
        List<String> permissions = userMapper.selectPermissionsByUserId(user.getId());
        return User.withUsername(username)
                   .password(user.getPassword())
                   .authorities(permissions.toArray(new String[]{})).build();
    }
}
